<?php


namespace app\api\controller\v21;


use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlFeedbackHotQuestion;
use app\common\cachemodel\ZlFeedbackQuestion;
use app\common\cachemodel\ZlFeedbackQuestionInfo;
use app\common\cachemodel\ZlFeedbackTag;
use app\common\lib\Util;
use think\Env;
use think\response\Json;

class Feedback extends Auth
{

    protected $domain_wap = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->domain_wap = Env::get('host.wap_domain');
    }

    /**
     * 把app里的header里的内容通过参数传到webview里
     */
    public function redirectUrl()
    {
        $headers = request()->header();
        $h = input('h/d', 0);
        $url = $this->domain_wap . '/zhunle_wap_feedback?token=' . $headers['access-token'] . '&app_type=' . $headers['app-type'] . '&did=' . $headers['did'] . '&model=' . $headers['model'] . '&sign=' . $headers['sign'] . '&time=' . $headers['time'] . '&version=' . $headers['version'] . '&phone_version=' . $headers['phone-version'] . '&h=' . $h;
//        http://192.168.0.193:8089/zhunle_wap_feedback?token=+j193+Bv4MUkRfHPfpFsYvFZJ//Yxa04IiCqHYK2XDH3A5haG2gnRNZDx6qohQnluP00gJGgRTjWOuS3Zw99tA==&app_type=ios&did=F5161CED-FDE8-4E24-8CA7-3E05D1A5F659&model=iPhone 7&sign=KkzHDPmQm+bVGlH9DqB6Wl5GhjlgQIK79bG+tKhq5s49Af8im900nL3hsulEo1F0EIHjqSNTAiblMjSXnaIfZKo+BFF2KsefCynnj/+d5GgCP+Ujh5zdBIdBaphzD7w97i+Z/0Gh/gB5b9P+KeJtHHuaTH0qjKYv6xsxUsxRNNU=&time=1621905916&version=2.5.5&phone_version=ios:13.5.1&h=20
        $this->redirect($url);
    }

    /**
     * 获取反馈热门问题列表
     * @return Json
     * @throws \Exception
     */
    public function getHotQuestionList()
    {
        $data = (new ZlFeedbackHotQuestion())->getQuestionList();
        if ($data['data'])
        {
            foreach ($data['data'] as $key => $datum)
            {
                unset($data['data'][$key]['sort']);
            }
        }
        $data['is_new_reply'] = ((new ZlFeedbackQuestion())->getUserHasNewMsg($this->user['id'])) ? 1 : 0;
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取热门反馈热门信息
     * @throws \Exception
     */
    public function getHotQuestionDetail()
    {
        $id = input('id/d', 0);
        $questionModel = new ZlFeedbackHotQuestion();
        $detail = $questionModel->getQuestionDetail($id);
        if ($detail)
        {
            return show(config('code.success'), '请求成功', $detail);
        }
        return show(config('code.error'), '数据不存在');
    }

    /**
     * 获取反馈标签
     * @throws \Exception
     */
    public function getTag()
    {
        $tags = (new ZlFeedbackTag())->getTags(1, ['id', 'name']);

        $resData = [];
        foreach ($tags as $item)
        {
            $resData[] = [
                'id' => (int)$item['id'],
                'name' => $item['name']
            ];
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取历史反馈信息
     */
    public function getFeedbackList()
    {
        $data = (new ZlFeedbackQuestion())->getFeedbackList($this->user['id']);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 意见反馈
     */
    public function feedbackAdd()
    {
        $tid = input('tid/d', 0);   // 反馈标签
        $content = trim(input('content/s', ''));   // 反馈内容
        $contentImg = trim(input('content_img/s', ''));    // 反馈的图片
        $contact = trim(input('contact/s', ''));   // 联系方式
        $phoneInfo = input('phone_info/s', '');  // 设备信息
        // /**
        //  * 设备：HUAWEI EML-AL00 EML
        //  * 操作系统： Android系统版本：10
        //  * 网络：2G/3G运营商：中国电信
        //  * 分辨率：2159x1080是否越狱：false
        //  * 产品版本：2.4.3扩展信息: {"uid":15243216,"通知状态":"开启"}
        //  */
        // $phoneInfo = [
        //     'app_version' => 'APP版本',    // APP版本
        //     'phone_type' => '手机型号',     // 手机型号
        //     'phone_system' => '手机操作系统',   // 手机操作系统
        //     'phone_system_version' => '手机操作系统版本',   // 手机操作系统版本
        //     'network' => '网络',    // 网络
        //     'operator' => '运营商',   // 运营商
        //     'resolution' => '分辨率', // 分辨率
        //     'feedback_message_attri' => '扩展信息'   // 扩展信息
        // ];

        if (!in_array($tid, (new ZlFeedbackTag())->getTagIds(1), true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (mb_strlen($content) < 5)
        {
            return show(config('code.error'), '内容至少5个字');
        }
        $phoneInfoArr = json_decode($phoneInfo, true);

        $appVersion = $this->headers['version'] ?? ($phoneInfoArr['app_version'] ?? ''); // APP版本
        $phoneType = $phoneInfoArr['phone_type'] ?? '';
        $phoneSystem = $phoneInfoArr['phone_system'] ?? '';

        $data = [
            'tid' => $tid,
            'uid' => $this->user['id'],
            'question' => $content,
            'question_img' => $contentImg,
            'app_version' => $appVersion,
            'phone_type' => $phoneType,
            'contact' => $contact,
            'phone_system' => $phoneSystem,
            'phone_info' => $phoneInfo,
            'admin_has_msg' => 1
        ];

        if (Util::commentCheck($this->user['id'], $data))
        {
            return show(config('code.error'), '别心急，等一等');
        }

        $data['last_reply_time'] = $this->request->time();
        $data['create_time'] = $this->request->time();

        $res = (new ZlFeedbackQuestion())->saveData($this->user['id'], $data);

        if ($res)
        {   // 反馈成功
            // 自动回复
            (new ZlFeedbackQuestionInfo())->systemReply($res);
            return show(config('code.success'), '反馈成功', ['fid' => $res]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取 意见反馈 详情
     */
    public function getFeedbackDetail()
    {
        $fqid = input('fid/d', 0);
        $page = input('page/d', 1);

        if (!$fqid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $feedbackQuestionModel = new ZlFeedbackQuestion();
        $feedbackInfo = $feedbackQuestionModel->getInfoById($fqid, ['create_time', 'question_img', 'question', 'uid', 'user_has_msg']);

        if (!$feedbackInfo || (int)$feedbackInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常；该反馈不存在');
        }

        if ($feedbackInfo['user_has_msg'])
        {   // 消息已读 处理
            $feedbackQuestionModel->save(['user_has_msg' => 0, 'update_time' => $this->request->time()], ['id' => $fqid]);
            $feedbackQuestionModel->newMsgdel($this->user['id'], $fqid);
        }

        $feedbackReplyList = (new ZlFeedbackQuestionInfo())->getReplyList($fqid, $page);

        $host = Env::get('host.photo');
//            $userAvatar = $host . config('feedback.user_avatar');//默认的用户头像
        $userAvatar = $host . $this->user['avatar'];//改为用户头像

        //替换用户头像
        foreach ($feedbackReplyList['data'] as $k => $v)
        {
            if ($v['isself'])
            {
                $feedbackReplyList['data'][$k]['avatar'] = $userAvatar;
            }
        }

        if ($page === 1)
        {   // 如果是第一页 将反馈信息添加到 会话信息前面


            $feedbackList[] = [
                'id' => 0,
                'avatar' => $userAvatar,
                'content' => $feedbackInfo['question'],
                'content_type' => 1,
                'create_time' => date('Y-m-d', $feedbackInfo['create_time']),
                'isself' => 1
            ];

            if ($feedbackInfo['question_img'])
            {   // 如果反馈的时候上传了图片
                $questionImgList = explode(',', $feedbackInfo['question_img']);
                foreach ($questionImgList as $questionImgItem)
                {
                    array_unshift($feedbackList, [
                        'id' => 0,
                        'avatar' => $userAvatar,
                        'content' => $host . $questionImgItem,
                        'content_type' => 2,
                        'create_time' => date('Y-m-d', $feedbackInfo['create_time']),
                        'isself' => 1
                    ]);
                }
            }

            $feedbackReplyList['data'] = array_merge($feedbackReplyList['data'], $feedbackList);
        }

        return show(config('code.success'), '请求成功', $feedbackReplyList);
    }

    /**
     * 反馈回复
     */
    public function feedbackReply()
    {
        $fqid = input('fid/d', 0);
        $contentType = input('content_type/d', 0);
        $content = trim(input('content/s', ''));

        if (!$fqid || !in_array($contentType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (!$content)
        {
            return show(config('code.error'), '请输入回复内容～');
        }

        $feedbackQuestionModel = new ZlFeedbackQuestion();
        $feedbackInfo = $feedbackQuestionModel->getInfoById($fqid, ['uid']);

        if (!$feedbackInfo || (int)$feedbackInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常；该反馈不存在');
        }

        $data = [
            'fq_id' => $fqid,
            'reply_attr' => 1,
            'uid' => $this->user['id'],
            'aid' => 0,
            'content' => $content,
            'content_type' => $contentType,
            'create_time' => $this->request->time()
        ];

        $res = (new ZlFeedbackQuestionInfo())->saveData($fqid, $data);

        if ($res)
        {
            return show(config('code.success'), '回复成功', [
                'id' => (int)$res,
                'avatar' => Env::get('host.photo') . $this->user['avatar'],//改为用户头像
                'content' => $content,
                'content_type' => $contentType,
                'create_time' => date('Y-m-d', $this->request->time()),
                'isself' => 1,
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取最新回复消息
     */
    public function newReplyMsg()
    {
        $fqid = input('fid/d', 0);
        $msgId = input('msg_id/d', 0);

        if (!$fqid || !$msgId)
        {
            return [];
        }

        $data = (new ZlFeedbackQuestionInfo())->getNewData($fqid, $msgId);

        return show(config('code.success'), '请求成功', $data);
    }
}
